<!-- ProductView.vue -->
<template>
  <div class="product-management-container">
    <div class="page-header">
      <span class="page-title">商品管理</span>
    </div>

    <!-- 商品搜索卡片 -->
    <el-card class="search-card">
      <el-form :inline="true" class="search-form">
        <el-form-item label="商品名称">
          <el-input
            placeholder="请输入商品名称"
            v-model="searchForm.productName"
            @keydown.enter="loadProducts">
          </el-input>
        </el-form-item>
        <el-form-item label="积分范围">
          <el-col :span="11">
            <el-input
              placeholder="最小积分"
              v-model="searchForm.minPoints"
              type="number">
            </el-input>
          </el-col>
          <el-col class="line" :span="2" style="text-align: center;">-</el-col>
          <el-col :span="11">
            <el-input
              placeholder="最大积分"
              v-model="searchForm.maxPoints"
              type="number">
            </el-input>
          </el-col>
        </el-form-item>
        <el-form-item class="form-buttons">
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadProducts">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品列表卡片 -->
    <el-card class="table-card">
      <el-table :data="productList" class="product-table">
        <el-table-column label="编号" type="index" width="80" align="center"/>
        <el-table-column label="商品名称" prop="productName" align="center" />
        <el-table-column label="所需积分" prop="pointsRequired" align="center" />
        <el-table-column label="库存数量" prop="quantity" align="center" />
        <el-table-column label="商品图片" align="center">
          <template #default="scope">
            <el-image
              v-if="scope.row.imageUrl"
              :src="getImageUrl(scope.row.imageUrl)"
              class="product-image"
              :preview-src-list="[getImageUrl(scope.row.imageUrl)]"
              preview-teleported>
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createdAt" align="center" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <div class="action-buttons">
              <el-button link type="primary" @click="editProduct(scope.row)">编辑</el-button>
              <el-button link type="danger" @click="deleteProduct(scope.row.productId, scope.row.productName)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-empty v-if="productList.length === 0 && !loading" description="暂无数据" />
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.pageNum"
          :page-sizes="[5, 10, 15]"
          :page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage"
      />
    </el-card>

    <!-- 编辑商品弹窗 -->
    <el-dialog
      title="编辑商品"
      class="product-dialog"
      v-model="editDialogVisible"
      :before-close="handleEditClose"
      width="600px">
      <el-form
        label-width="100px"
        label-position="top"
        class="dialog-form"
        ref="editFormRef"
        :model="editForm"
        :rules="formRules">

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="商品名称" prop="productName">
              <el-input
                placeholder="请输入商品名称"
                v-model="editForm.productName">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所需积分" prop="pointsRequired">
              <el-input-number
                v-model="editForm.pointsRequired"
                :min="0"
                placeholder="请输入所需积分"
                style="width: 100%;">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存数量" prop="quantity">
              <el-input-number
                v-model="editForm.quantity"
                :min="0"
                placeholder="请输入库存数量"
                style="width: 100%;">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="商品图片" prop="imageUrl">
              <el-upload
                class="product-uploader"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleImageSuccess"
                :on-error="handleImageError"
                :before-upload="beforeImageUpload"
                :disabled="uploading">
                <img v-if="editForm.imageUrl" :src="getImageUrl(editForm.imageUrl)" class="product-image-preview">
                <el-icon v-else class="product-uploader-icon"><Plus /></el-icon>
                <div class="upload-text" v-if="!editForm.imageUrl">点击上传图片</div>
              </el-upload>
              <div class="image-url-display" v-if="editForm.imageUrl">
                <el-input
                  v-model="editForm.imageUrl"
                  readonly
                  class="image-url-input">
                  <template #append>
                    <el-button @click="editForm.imageUrl = ''">清除</el-button>
                  </template>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="描述1" prop="description1">
              <el-input
                type="textarea"
                placeholder="请输入商品描述1"
                v-model="editForm.description1"
                :rows="3">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="描述2" prop="description2">
              <el-input
                type="textarea"
                placeholder="请输入商品描述2"
                v-model="editForm.description2"
                :rows="3">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="handleEditClose">取消</el-button>
        <el-button
          type="primary"
          @click="updateProduct"
          :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { Plus } from '@element-plus/icons-vue'

// 数据列表
const productList = ref([])

const totalPage = ref(0);

// 搜索表单
const searchForm = ref({
  productName: '',
  minPoints: '',
  maxPoints: '',
  pageNum: 1,
  pageSize: 5
})

// 编辑弹窗
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  productId: '',
  productName: '',
  pointsRequired: 0,
  description1: '',
  description2: '',
  imageUrl: '',
  quantity: 0,
  createdAt: ''
})

// 上传状态
const uploading = ref(false)
const saving = ref(false)

// 上传配置
const uploadUrl = `${BASE_URL}/api/files/upload`
const uploadHeaders = {
  // 如果需要认证token，可以在这里添加
  // 'Authorization': 'Bearer ' + localStorage.getItem('token')
}

// 表单验证规则
const formRules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  pointsRequired: [
    { required: true, message: '请输入所需积分', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入库存数量', trigger: 'change' }
  ]
}

// 页面加载时获取商品列表
onMounted(() => {
  loadProducts()
})

// 加载商品列表
const loadProducts = () => {
  axios.get(BASE_URL + '/api/products/select' , {params:searchForm.value})
    .then(response => {
      if (response.data.state === 2001) {
        productList.value = response.data.data.list;
        totalPage.value = response.data.data.totalPage;
      } else {
        ElMessage.error(response.data.msg)
      }
    })
    .catch(error => {
      ElMessage.error('获取商品列表失败: ' + error.message)
    })
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    productName: '',
    minPoints: '',
    maxPoints: '',
    pageNum: 1,
    pageSize: 5
  }
  loadProducts()
}

// 编辑商品
const editProduct = (product) => {
  Object.assign(editForm, product)
  editDialogVisible.value = true
}

// 图片上传前检查
const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }

  uploading.value = true
  return true
}

// 图片上传成功处理
const handleImageSuccess = (response, uploadFile) => {
  uploading.value = false
  if (response.state === 2001) {
    editForm.imageUrl = response.data.url
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.msg || '图片上传失败')
  }
}

// 图片上传失败处理
const handleImageError = (error) => {
  uploading.value = false
  ElMessage.error('图片上传失败: ' + error.message)
}

// 更新商品
const updateProduct = () => {
  if (!editFormRef.value) return

  editFormRef.value.validate((valid) => {
    if (valid) {
      saving.value = true

      axios.put(BASE_URL + '/api/products/update', editForm)
        .then(response => {
          if (response.data.state === 2001) {
            ElMessage.success('商品更新成功')
            handleEditClose()
            loadProducts()
          } else {
            ElMessage.error(response.data.msg)
          }
        })
        .catch(error => {
          ElMessage.error('商品更新失败: ' + error.message)
        })
        .finally(() => {
          saving.value = false
        })
    }
  })
}

// 关闭编辑弹窗
const handleEditClose = () => {
  editDialogVisible.value = false
  Object.assign(editForm, {
    productId: '',
    productName: '',
    pointsRequired: 0,
    description1: '',
    description2: '',
    imageUrl: '',
    quantity: 0,
    createdAt: ''
  })
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 删除商品
const deleteProduct = (productId, productName) => {
  ElMessageBox.confirm(
    `确定要删除商品 "${productName}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    axios.delete(BASE_URL + `/api/products/delete/id/${productId}`)
      .then(response => {
        if (response.data.state === 2001) {
          ElMessage.success('商品删除成功')
          loadProducts()
        } else {
          ElMessage.error(response.data.msg)
        }
      })
      .catch(error => {
        ElMessage.error('商品删除失败: ' + error.message)
      })
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const handleSizeChange = (pageSize) => {
  searchForm.value.pageSize = pageSize;
  loadProducts();
}

const handleCurrentChange = (pageNum) => {
  searchForm.value.pageNum = pageNum;
  loadProducts();
}

// 处理图片URL，确保正确的路径
const getImageUrl = (imageUrl) => {
  // 如果是/static/imgs/products/路径，映射到实际的/imgs/products/路径
  if (imageUrl && (imageUrl.includes('/static/imgs/products/') || imageUrl.startsWith('/static/imgs/products/'))) {
    return imageUrl.replace('/static/imgs/products/', '/imgs/products/');
  }
  // 其他情况直接返回
  return imageUrl || '';
}
</script>

<style scoped>
.product-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.search-form :deep(.el-form-item__label) {
  font-weight: 500;
  margin-right: 8px;
}

.form-buttons {
  margin-left: auto;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-table {
  width: 100%;
}

.product-table :deep(th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.product-table :deep(.el-table__row) {
  height: 60px;
}

.product-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.product-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.product-dialog {
  border-radius: 12px;
}

.dialog-form {
  padding: 10px 0;
}

.dialog-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.dialog-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.product-uploader {
  width: 100%;
  display: block;
}

.product-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 100%;
  height: 178px;
}

.product-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.product-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-image-preview {
  width: 100%;
  height: 178px;
  object-fit: cover;
  display: block;
}

.upload-text {
  position: absolute;
  bottom: 10px;
  width: 100%;
  text-align: center;
  color: #909399;
  font-size: 12px;
}

.image-url-display {
  margin-top: 10px;
}

.image-url-input {
  width: 100%;
}

:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

.line {
  text-align: center;
}
</style>
